<template>
  <div>
    <el-tag
      v-for="tag in dynamicTags"
      :key="tag"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="saveTagInput"
      v-model="inputValue"
      class="input-new-tag"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
  </div>
</template>

<script>
import { putGoodsAttributes } from '@/api/Taxonomies.js'
export default {
  props: {
    // 渲染数据
    tableData: {
      type: String,
      required: true
    },
    // 全部数据
    allData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
      // judgeUnique: false
    }
  },

  created() {
    this.addAssignment()
  },

  methods: {
    addAssignment() {
      // arrAddUnique.judgeUnique = false
      if (this.tableData === '') {
        this.dynamicTags = []
      } else {
        const arrAddUnique = this.tableData.split(',')
        this.dynamicTags = arrAddUnique
      }
    },
    // 删除
    async handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      this.allData.attr_vals = this.dynamicTags.join()
      const res = await putGoodsAttributes(this.allData)
      this.$message.success('删除成功')
      console.log(res)
      this.$emit('dataFeedback', res)
    },
    // 显示输入
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 处理输入确认
    async handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
        this.allData.attr_vals = this.dynamicTags.join()
        const res = await putGoodsAttributes(this.allData)
        this.$message.success('添加成功')
        console.log(res)
        this.$emit('dataFeedback', res)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style scoped lang='scss'>
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
